<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">{{ isNewDevice ? '设备注册' : '设备登录' }}</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="序列号" prop="sn">
          <el-input v-model="loginForm.sn"></el-input>
        </el-form-item>
        <el-form-item v-if="showPassword" label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item v-if="isNewDevice && showPassword" label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="loginForm.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!showPassword" type="primary" @click="handleNext">下一步</el-button>
          <el-button v-if="showPassword" type="primary" @click="submitForm">
            {{ isNewDevice ? '注册' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default defineComponent({
  name: 'LoginPage',
  setup() {
    const loginForm = reactive({
      sn: '',
      password: '',
      confirmPassword: ''
    })

    const rules = reactive<FormRules>({
      sn: [{ required: true, message: '请输入设备SN号', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      confirmPassword: [{ required: true, message: '请再次输入密码', trigger: 'blur' }]
    })

    const loginFormRef = ref<FormInstance>()
    const router = useRouter()
    const showPassword = ref(false)
    const isNewDevice = ref(false)

    const handleNext = async () => {
      if (!loginFormRef.value) return
      await loginFormRef.value.validateField('sn', async (valid) => {
        if (valid) {
          console.log('设备SN号校验通过')
          try {
            const response = await axios.post('/api/check_device', {
              sn: loginForm.sn
            })
            const { exists, message } = response.data
            console.log('检查设备SN号接口响应数据:', response.data)
            if (exists) {
              console.log('设备SN号已存在,检查是否设置过密码')
              const passwordResponse = await axios.post('/api/check_password_set', {
                sn: loginForm.sn
              })
              const { password_set, message: passwordMessage } = passwordResponse.data
              console.log('检查设备是否设置过密码的响应数据:', passwordResponse.data)
              if (password_set) {
                console.log('设备已设置密码,显示密码输入框')
                showPassword.value = true
              } else {
                console.log('设备未设置密码,进入设置密码流程', passwordMessage)
                isNewDevice.value = true
                // 显示提示框
                await ElMessageBox.alert('这是您的设备首次初始化,请设置登录密码', '提示', {
                  confirmButtonText: '确定',
                  type: 'warning'
                })
                // 显示密码输入框
                showPassword.value = true
              }
            } else {
              console.log('设备SN号不存在', message)
              ElMessageBox.alert('设备SN号不存在', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              })
            }
          } catch (error) {
            console.log('请求错误:', error)
            ElMessage.error('请求错误,请稍后重试')
          }
        } else {
          console.log('设备SN号校验失败')
        }
      })
    }

    const submitForm = async () => {
      if (!loginFormRef.value) return
      if (showPassword.value) {
        await loginFormRef.value.validate((valid) => {
          if (valid) {
            console.log('表单校验通过')
            if (isNewDevice.value) {
              // 新设备注册
              if (loginForm.password !== loginForm.confirmPassword) {
                console.log('两次输入的密码不一致')
                ElMessage.warning('两次输入的密码不一致')
                return
              }
              // 发送注册请求
              axios
                .post('/api/register_device', {
                  sn: loginForm.sn,
                  password: loginForm.password
                })
                .then((response) => {
                  const { success, message } = response.data
                  if (success) {
                    console.log('注册成功')
                    ElMessage.success(message)
                    // 注册成功后,标记设备已注册
                    localStorage.setItem('deviceRegistered', 'true')
                    // 重置表单状态
                    isNewDevice.value = false
                    showPassword.value = false
                    loginForm.password = ''
                    loginForm.confirmPassword = ''
                  } else {
                    console.log('注册失败:', message)
                    ElMessage.warning(message)
                  }
                })
                .catch((error) => {
                  console.log('请求错误:', error)
                  ElMessage.error('请求错误,请稍后重试')
                })
            } else {
              // 已注册设备登录
              // 发送登录请求
              axios
                .post('/api/auth_device', {
                  sn: loginForm.sn,
                  password: loginForm.password
                })
                .then((response) => {
                  const { success, message, token } = response.data
                  if (success) {
                    console.log('登录成功')
                    // 登录成功后,将 token 存储在本地存储中
                    localStorage.setItem('token', token)
                    console.log('Token 已存储:', token)
                    // 跳转到 Dashboard 页面
                    router.replace('/dashboard')
                    console.log('已跳转到 Dashboard 页面')
                  } else {
                    console.log('登录失败:', message)
                    ElMessage.error(message)
                  }
                })
                .catch((error) => {
                  console.log('请求错误:', error)
                  ElMessage.error('请求错误,请稍后重试')
                })
            }
          } else {
            console.log('表单校验失败')
            return false
          }
        })
      }
    }

    return {
      loginForm,
      rules,
      loginFormRef,
      showPassword,
      isNewDevice,
      handleNext,
      submitForm
    }
  }
})
</script>

<style scoped>
body,
html {
  margin: 0;
  padding: 0;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%);
}

.login-box {
  width: 400px;
  padding: 0 40px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #6a67ce;
  font-size: 24px;
}

.login-form {
  margin-top: 20px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.el-button--primary {
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}
</style>